

import imageClassifying.IDistance;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class KNN {
	IDistance disCalc;
	
	public KNN(IDistance disCalc){
		this.disCalc = disCalc;
	}
	
	private List<ImageDistancePair> SortDistances(ImageData image, List<ImageData> imageSet) {
		ArrayList<ImageDistancePair> distanceList = new ArrayList<ImageDistancePair>();
		
		for (ImageData currImage : imageSet) {
			double distance = disCalc.calculateDistance(image.getVector(),currImage.getVector());
			distanceList.add(new ImageDistancePair(distance, currImage));
		}
		
		Collections.sort(distanceList);
		return distanceList;
	}
	
	public void regressImage(ImageData image,List<ImageData> imageSet, int k) {
		
		List<ImageDistancePair> distanceList = SortDistances(image,imageSet);
		double resultX = 0;
		double resultY = 0;
		double sum =0;
		
		for (int i = 0; i < Math.min(k,distanceList.size()); i++) {			
			resultX+=distanceList.get(i).getImage().getX() /distanceList.get(i).getDistance();
			resultY+=distanceList.get(i).getImage().getY() /distanceList.get(i).getDistance();
			sum+= 1/distanceList.get(i).getDistance();
		}
		image.setXY(resultX/sum,resultY/sum);
		imageSet.add(image);
	}
}
